package com.the_last.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.the_last.mapper.SportTypeMapper;
import com.the_last.pojo.po.SportType;
import com.the_last.service.SportTypeService;
import com.the_last.utils.RedisUtil;
import com.the_last.utils.Result;
import jakarta.annotation.Resource;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.List;

/**
 * @description 针对表【sport_type】的数据库操作Service实现
 */
@Service
public class SportTypeServiceImpl extends ServiceImpl<SportTypeMapper, SportType>
        implements SportTypeService {
    
    @Resource
    private RedisUtil redisUtil;
    
    @Resource
    private RedissonClient redissonClient;
    
    /**
     * 清除运动类型相关的所有缓存
     */
    private void clearSportTypeCache() {
        redisUtil.delete("sport:type:all");
        redisUtil.delete("venue:tree"); // 同时清除场馆树形结构缓存
    }
    
    @Override
    public Result<List<SportType>> getAllSportTypes() {
        // 缓存key
        String cacheKey = "sport:type:all";
        
        // 尝试从缓存获取
        List<SportType> cached = redisUtil.getList(cacheKey, SportType.class);
        if (!CollectionUtils.isEmpty(cached)) {
            return Result.success(cached);
        }
        
        // 获取分布式锁
        String lockKey = "lock:sport:type:all";
        RLock lock = redissonClient.getLock(lockKey);
        
        try {
            lock.lock();
            
            // 双重检查
            cached = redisUtil.getList(cacheKey, SportType.class);
            if (!CollectionUtils.isEmpty(cached)) {
                return Result.success(cached);
            }
            
            // 从数据库查询
            List<SportType> list = this.lambdaQuery()
                    .eq(SportType::getDeleted, 0)  // 只查询未删除的
                    .orderByAsc(SportType::getId)
                    .list();
            
            // 存入缓存
            if (!CollectionUtils.isEmpty(list)) {
                redisUtil.setList(cacheKey, list);
            }
            
            return Result.success(list);
        } finally {
            lock.unlock();
        }
    }
}